package com.survey.wxapp.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class WxLoginUtil {

    public static String getAccessToken(String appId, String secret) throws Exception {

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        // Read the response
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();
        // Parse JSON to get access_token
        return content.toString(); // 实际应用中应该解析JSON字符串获取access_token
    }

    public static String getUserPhoneNumber(String code, String accessToken) throws Exception {
        String requestUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setDoOutput(true);
        // 构建请求体
        String requestBody = "{\"code\":\"" + code + "\"}";
        // 发送请求体
        try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {
            writer.write(requestBody);
            writer.flush();
        }
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder content = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        connection.disconnect();
        // 返回响应内容
        return content.toString();
    }

    public static String getPhoneNumber(String code, String appId, String secret) throws Exception {
        String JsonObject = WxLoginUtil.getAccessToken(appId, secret);
        System.out.println("JsonObject" + JsonObject);
        JSONObject jsonObject = JSONObject.parseObject(JsonObject);
        String accessToken = jsonObject.getString("access_token");
        String userPhoneNumber = WxLoginUtil.getUserPhoneNumber(code, accessToken);
        JSONObject userPhoneNumberJson = JSONObject.parseObject(userPhoneNumber);
        JSONObject phoneInfo = userPhoneNumberJson.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getString("phoneNumber");
        return phoneNumber;
    }

    public String getOpenId(String code, String appId, String appSecret) {
        String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String url = String.format(GET_OPENID_URL, appId, appSecret, code);
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");

            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                // 解析 JSON 响应
                JSONObject jsonObject = JSONObject.parseObject(response.toString());
                if (jsonObject.containsKey("openid")) {
                    return jsonObject.getString("openid");
                } else {
                    throw new RuntimeException("Failed to get openId: " + jsonObject.toString());
                }
            } finally {
                con.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to get openId", e);
        }
    }
}